﻿using IDEAMS.core;
using IDEAMS.core.deviceClient;
using IDEAMS.model;
using IDEAMS.model.device;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace IDEAMS.view
{
    /// <summary>
    /// AddDeviceDlg.xaml 的交互逻辑
    /// </summary>
    public partial class AddDeviceDlg : Window
    {
        public AddDeviceDlgViewModel windowViewModel;
        public AddDeviceDlg()
        {
            InitializeComponent();

            windowViewModel = new AddDeviceDlgViewModel();
            this.DataContext = windowViewModel;

            this.Closing += new System.ComponentModel.CancelEventHandler(Window_Closing);

            this.btnOK.Click += new RoutedEventHandler(OK_Click);
            this.btnCancel.Click += new RoutedEventHandler(Cannel_Click);

            TW_App.delegateCollection.sendDeviceParamEvent += SaveDeviceParamEvent;
            TW_App.delegateCollection.sendDeviceFrequencyEvent += SaveDeviceFrequencyEvent;
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            TW_App.delegateCollection.sendDeviceParamEvent -= SaveDeviceParamEvent;
            TW_App.delegateCollection.sendDeviceFrequencyEvent -= SaveDeviceFrequencyEvent;
        }

        private void SaveDeviceParamEvent(DeviceParam deviceParam)
        {
            //if (windowViewModel.deviceInfo.serialNo.Equals(deviceParam.serialNo))
            //{
            //    windowViewModel.deviceInfo.deviceParam.Copy(deviceParam);
            //}
        }

        private void SaveDeviceFrequencyEvent(string serialNo, int frequency)
        {
            //if (windowViewModel.deviceInfo.serialNo.Equals(serialNo))
            //{
            //    windowViewModel.deviceInfo.frequency = frequency;
            //}
        }

        private void OK_Click(object sender, RoutedEventArgs e)
        {
            if (!CheckInput())
            {
                return;
            }

            List<DeviceInfo> deviceInfoList = TW_App.deviceInfoCollection.ToList();
            for (int i = 0; i < deviceInfoList.Count; i++)
            {
                if (deviceInfoList[i].ip.Equals(windowViewModel.deviceInfo.ip))
                {
                    string errMsg = string.Format("已存在ip为 {0} 的设备，不能重复添加。", windowViewModel.deviceInfo.ip);
                    MessageBox.Show(errMsg, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    return;
                }
            }


            DeviceClient deviceClient = new DeviceClient(windowViewModel.deviceInfo.ip, windowViewModel.deviceInfo.port);
            int rn = deviceClient.dataWorker.Connect(new Action<DeviceParam,int>((DeviceParam deviceParam,int frequency) => {
                if (deviceParam != null)
                {
                    deviceClient.deviceParam = new DeviceParam(deviceParam);
                    TW_App.delegateCollection.SyncSendDeviceParam(deviceParam);
                }
                if (frequency != 0)
                {
                    deviceClient.frequency = frequency;
                    TW_App.delegateCollection.SyncSendDeviceFrequency(deviceParam.serialNo, frequency);
                }
            }));

            deviceClient.StartAsync(new Action<DeviceParam,int>((DeviceParam deviceParam,int frequency) =>
            {
                if (deviceParam != null)
                {
                    deviceClient.deviceParam = new DeviceParam(deviceParam);
                    TW_App.delegateCollection.SyncSendDeviceParam(deviceParam);
                }
                if (frequency != 0)
                {
                    deviceClient.frequency = frequency;
                    TW_App.delegateCollection.SyncSendDeviceFrequency(deviceParam.serialNo, frequency);
                }
            }));
            //int rn = deviceClient.StartAsync(new Action<DeviceParam>((DeviceParam deviceParam) =>
            //{
            //    if (deviceParam != null)
            //    {
            //        windowViewModel.deviceParam = deviceParam;
            //    }
            //}));

            if (rn != 0)
            {
                string errMsg = string.Format("设备({0}:{1})连接失败", windowViewModel.deviceInfo.ip,windowViewModel.deviceInfo.port);
                MessageBox.Show(errMsg,"错误",MessageBoxButton.OK,MessageBoxImage.Error);
                return;
            }

            //deviceClient.deviceParam = windowViewModel.deviceParam;
            windowViewModel.deviceParam = deviceClient.deviceParam;

            DeviceInfo deviceInfo = TW_App.deviceInfoCollection.Find(windowViewModel.deviceParam.serialNo);
            if (deviceInfo != null)
            {
                MessageBox.Show("序列号为[{0}]的设备已经存在于烤机列表中", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                deviceClient.Stop();
                return;
            }

            RoasterRecord roasterRecord = TW_App.roasterRecordCollection.Find(windowViewModel.deviceParam.serialNo);
            if(roasterRecord != null)
            {
                MessageBoxResult? result = MessageBox.Show("检测到该设备存在完成的检测记录，是否继续添加？", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if(result == MessageBoxResult.Yes)
                {
                    DeviceInfo info = new DeviceInfo();
                    info.Load(windowViewModel.deviceParam.serialNo);
                    windowViewModel.deviceInfo = new DeviceInfoViewModel(info);
                }
                else
                {
                    deviceClient.Stop();
                    return;
                }
            }
            else
            {
                windowViewModel.deviceInfo.serialNo = windowViewModel.deviceParam.serialNo;
                windowViewModel.deviceInfo.deviceParam.Copy(windowViewModel.deviceParam);
                //windowViewModel.deviceInfo.step = ProcessStep.PRE_ETALON;
                windowViewModel.deviceInfo.step = (ProcessStep)TW_App.globalSetting.inspectionSequences[0];
            }

            TW_App.deviceClientManager.Add(windowViewModel.deviceParam.serialNo, deviceClient);
            //windowViewModel.deviceInfo.serialNo = windowViewModel.deviceParam.serialNo;
            //windowViewModel.deviceInfo.step = ProcessStep.PRE_ETALON;
            TW_App.deviceInfoCollection.Add(new DeviceInfo(windowViewModel.deviceInfo));
            TW_App.deviceInfoCollection.Save();

            this.DialogResult = true;
        }

        private void Cannel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private bool CheckInput()
        {
            BindingExpression beDeviceIp = tbDeviceIp.GetBindingExpression(TextBox.TextProperty);
            beDeviceIp.UpdateSource();
            BindingExpression beDevicePort = tbDevicePort.GetBindingExpression(TextBox.TextProperty);
            beDevicePort.UpdateSource();

            bool hasError = (Validation.GetHasError(tbDeviceIp)
                || Validation.GetHasError(tbDevicePort));

            return !hasError;
        }
    }

    public class AddDeviceDlgViewModel : ViewModelBase
    {
        public DeviceParam deviceParam;

        public AddDeviceDlgViewModel()
        {
            deviceInfo = new DeviceInfoViewModel();
            deviceInfo.ip = "10.0.0.122";
            deviceInfo.port = 4010;
            deviceInfo.backgroundColor = new SolidColorBrush(Color.FromArgb(0xFF, 0xff, 0x00, 0xff));
        }

        private DeviceInfoViewModel m_deviceInfo;
        public DeviceInfoViewModel deviceInfo
        {
            get { return m_deviceInfo; }
            set
            {
                m_deviceInfo = value;
                NotifyPropertyChanged();
            }
        }
    }
}
